import Dep from './Dep.js';
//这是依赖的watcher类
let uid =0;
export default class Watcher{
	constructor(target,expression,callback){
		console.log('这是Watcher类的构造器=>',expression);
		this.uid =uid ++;
		this.target =target;
		this.getter =parsePath(expression);
		this.callback = callback;
		this.value = this.get();

	};
	update(){
		this.run();
	}
	get(){
		//进入依赖收集阶段，让全局的Dep.target设置为watcher本身
		Dep.target = this;
		const obj = this.target;
		let value;
		//只要能找就一直找
		try{
			value = this.getter(obj)
		}finally{
			Dep.target =null;
			console.log('Dep.target变成null了')
		};
		return value
	}
	run(){
		this.getAndInvoke(this.callback);

	}
	getAndInvoke(cb){
		const value = this.get();
		// console.log('啦啦啦',value,this.value)
		if(value !=this.value || typeof value=='object'){
			const oldValue = this.value;
			this.value =value;
			cb.call(this.target,value,oldValue);
		}
	}
};


function parsePath(str){
	var segements = str.split('.');
	return function (obj){
		for(let i=0;i<segements.length;i++){
			if(!obj) return ;
			obj = obj[segements[i]];
		}
		return obj
	}
}